package com.oracle.oa.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.oracle.oa.dao.MessageToUserDao;
import com.oracle.oa.entity.Messagetouser;

public class MessageToUserDaoImpl extends BaseDaoImpl implements
		MessageToUserDao {
	/**
	 * 根据收件人和是否阅读查询
	 */
	
	public List<Messagetouser> getByTouseridAndIfread(Object touserid,
			Object ifread) {
		List<Messagetouser> list=null;
		Session session = this.getHibernateTemplate().getSessionFactory()
				.openSession();
		try {
//			String hql=" from  Messagetouser as m where m.userinfo=:touserid and m.ifread=:ifread";
//			Query query = session.createQuery(hql);
//			
//			query.setParameter("touserid", touserid);
//			query.setParameter("ifread", ifread);
//			list = query.list();
			
			Criteria c = session.createCriteria(Messagetouser.class);
			c.add(Restrictions.eq("userinfo", touserid))
			 .add(Restrictions.eq("ifread", ifread));
			list = c.list();
			
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}

	/**
	 * 根据messageid进行分组查询，得到每个messageid发送的不重复收件人个数
	 */
	
	public Object getuserGroupByAnddistinct(Object messageid) {
		Object list = null;
		Session session = this.getHibernateTemplate().getSessionFactory()
				.openSession();
		//select messageid,count(distinct touserid) from messageToUser group by messageid; 
		try {
			Criteria c = session.createCriteria(Messagetouser.class);
			c.setProjection(Projections.projectionList()
					.add(Projections.countDistinct("userinfo.userid")))
					.add(Restrictions.eq("message.messageid", messageid));
			list=c.list();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}

	/**
	 * 批量删除，删除某个messageid的messagetouser数据
	 */
	
	public int deleteBymessageid(Object messageid) {
		int count=0;
		Session session = this.getHibernateTemplate().getSessionFactory()
				.openSession();
		//构建hql语句
		String hql="delete from Messagetouser as mtu where mtu.message.messageid=:messageid";
		count = session.createQuery(hql)
				.setParameter("messageid", messageid)
				.executeUpdate();
		
		session.close();
		return count;
	}
}
